import base64
import json

import requests


# client_id： 必须参数，应用的API Key；
# client_secret： 必须参数，应用的Secret Key；

def get_token():
    api_key = "UH1GvV7SW8F4kKNMDsGjAZ0R"
    sce_key = "adfT643jwOj77f9E0bqzzHEiIYBd1xMK";

    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={sce_key}"

    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)

    token_data = json.loads(response.text)

    refresh_token = token_data['refresh_token']
    token = token_data['access_token']
    print("refresh token:" + refresh_token)
    print("token:" + token)

    return token


def ask_calorie(token, image_path):
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish"
    # 二进制方式打开图片文件
    f = open(image_path, 'rb')
    img = base64.b64encode(f.read())

    params = {"image": img, "top_num": 5}
    access_token = token
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        print(response.json())


if __name__ == '__main__':
   token= get_token()
   ask_calorie(token,"/Users/zhengyunwang/Downloads/lunch_2.jpg")

